import { numberFormat } from '@/utils/formatterUtil';

const isNumber = obj => {
    const type = typeof obj;
    // eslint-disable-next-line no-restricted-globals
    return (type === 'number' || type === 'string') && !isNaN(obj - parseFloat(obj));
};

const convertToNumber = (value, needDecimal, decimalPlaces, thousandsSeparator = ',') => {
    let rel;

    if (value == null || String(value).length === 0) {
        return value;
    }
    // 去除非【数字】、非【-】、非【.】号的字符
    // 去除开头的【.】字符
    // 去除开头的【-.】中的【.】字符
    rel = String(value)
        .replace(/[^\d\-.]/g, '')
        .replace(/^\./g, '')
        .replace(/^-\./g, '-');

    // 去除字符串第1个字符后的【-】减号-1-3-4 =>-134
    if (rel.length > 1) {
        const [firstChar, ...other] = rel;
        rel = firstChar + other.join('').replace(/-/g, '');
    }

    const lastDot = rel.indexOf('.');
    let integerPart;
    let decimalPart;
    let afterDotStr;

    if (lastDot >= 1) {
        integerPart = rel.substring(0, lastDot);
        afterDotStr = rel.substring(lastDot + 1);
        // 去除多余的【.】号
        decimalPart = afterDotStr.replace(/\./g, '');
    } else {
        integerPart = rel;
        afterDotStr = '';
        decimalPart = '';
    }

    if (needDecimal || decimalPart.length > 0) {
        rel = integerPart + (decimalPart ? '.' : '') + decimalPart;
    } else if (lastDot >= 1 && afterDotStr.length >= decimalPart.length) {
        rel = `${integerPart}.${decimalPart.substr(0, decimalPlaces ?? decimalPart.length)}`;
    }

    if (needDecimal || thousandsSeparator) {
        rel = numberFormat(rel, needDecimal ? decimalPlaces : null, thousandsSeparator);
    }

    return rel;
};

/**
 * 设置光标位置
 * @param {HTMLElement} inputEle 输入框
 * @param formatValue 格式化的元素
 * @param beforeLength 光标前面字符串的长度
 * @param thousandsSeparator 千分符
 */
const setCaretPosition = (inputEle, formatValue, beforeLength, thousandsSeparator) => {
    let positionWithoutSeparator = 0;
    let destIndex = null;

    if (!beforeLength) {
        inputEle.setSelectionRange(0, 0);
        return;
    }

    for (let i = 1; i <= formatValue.length; i += 1) {
        if (formatValue[i - 1] !== thousandsSeparator) {
            positionWithoutSeparator += 1;
        }

        if (positionWithoutSeparator === beforeLength) {
            destIndex = i;
            break;
        }
    }

    if (destIndex != null) {
        inputEle.setSelectionRange(destIndex, destIndex);
    }
};

export { convertToNumber, isNumber, setCaretPosition };
